#!/usr/bin/env node

/**
 * Chrome 扩展构建脚本
 * 支持开发和生产环境构建
 */

const fs = require('fs-extra');
const path = require('path');
const { minify } = require('terser');
const chalk = require('chalk');

class ChromeExtensionBuilder {
  constructor() {
    this.isDev = process.env.NODE_ENV === 'development';
    this.isWatch = process.argv.includes('--watch');
    this.srcDir = path.resolve(__dirname, '..');
    this.buildDir = path.resolve(__dirname, '../build');

    // 需要复制的文件和目录
    this.filesToCopy = [
      'manifest.json',
      'popup.html',
      'popup.css',
      'options.html',
      'options.css',
      'icons/',
      'native-host/'
    ];

    // 需要处理的 JS 文件
    this.jsFiles = [
      'background.js',
      'popup.js',
      'options.js',
      'hls-downloader.js'
    ];
  }

  async build() {
    console.log(chalk.blue(`🚀 开始构建 Chrome 扩展 (${this.isDev ? '开发' : '生产'}模式)`));

    try {
      // 清理构建目录
      await this.cleanBuildDir();

      // 复制静态文件
      await this.copyStaticFiles();

      // 处理 JavaScript 文件
      await this.processJavaScriptFiles();

      // 处理 manifest.json
      await this.processManifest();

      console.log(chalk.green('✅ 构建完成!'));

      if (this.isWatch) {
        this.startWatchMode();
      }

    } catch (error) {
      console.error(chalk.red('❌ 构建失败:'), error.message);
      process.exit(1);
    }
  }

  async cleanBuildDir() {
    console.log(chalk.yellow('🧹 清理构建目录...'));
    await fs.ensureDir(this.buildDir);
    await fs.emptyDir(this.buildDir);
  }

  async copyStaticFiles() {
    console.log(chalk.yellow('📁 复制静态文件...'));

    for (const file of this.filesToCopy) {
      const srcPath = path.join(this.srcDir, file);
      const destPath = path.join(this.buildDir, file);

      if (await fs.pathExists(srcPath)) {
        await fs.copy(srcPath, destPath);
        console.log(chalk.gray(`  ✓ ${file}`));
      }
    }
  }

  async processJavaScriptFiles() {
    console.log(chalk.yellow('⚙️  处理 JavaScript 文件...'));

    for (const jsFile of this.jsFiles) {
      const srcPath = path.join(this.srcDir, jsFile);
      const destPath = path.join(this.buildDir, jsFile);

      if (await fs.pathExists(srcPath)) {
        let content = await fs.readFile(srcPath, 'utf8');

        if (!this.isDev) {
          // 生产环境压缩代码
          const minified = await minify(content, {
            compress: {
              drop_console: true,
              drop_debugger: true
            },
            mangle: false, // Chrome 扩展不建议混淆变量名
            format: {
              comments: false
            }
          });

          if (minified.error) {
            throw new Error(`压缩 ${jsFile} 失败: ${minified.error}`);
          }

          content = minified.code;
        }

        await fs.writeFile(destPath, content);
        console.log(chalk.gray(`  ✓ ${jsFile} ${this.isDev ? '' : '(已压缩)'}`));
      }
    }
  }

  async processManifest() {
    console.log(chalk.yellow('📋 处理 manifest.json...'));

    const manifestPath = path.join(this.srcDir, 'manifest.json');
    const manifest = await fs.readJson(manifestPath);

    // 根据环境调整 manifest
    if (this.isDev) {
      manifest.name += ' (开发版)';
      // 开发环境可以添加额外的权限或配置
    } else {
      // 生产环境优化
      if (manifest.content_security_policy) {
        // 确保 CSP 策略适合生产环境
      }
    }

    const buildManifestPath = path.join(this.buildDir, 'manifest.json');
    await fs.writeJson(buildManifestPath, manifest, { spaces: 2 });
    console.log(chalk.gray('  ✓ manifest.json'));
  }

  startWatchMode() {
    console.log(chalk.blue('👀 启动监听模式...'));

    const chokidar = require('chokidar');

    const watcher = chokidar.watch([
      ...this.filesToCopy.map(f => path.join(this.srcDir, f)),
      ...this.jsFiles.map(f => path.join(this.srcDir, f))
    ], {
      ignored: /node_modules/,
      persistent: true
    });

    watcher.on('change', async (filePath) => {
      const relativePath = path.relative(this.srcDir, filePath);
      console.log(chalk.cyan(`📝 文件变更: ${relativePath}`));

      try {
        if (this.jsFiles.includes(relativePath)) {
          await this.processJavaScriptFiles();
        } else if (relativePath === 'manifest.json') {
          await this.processManifest();
        } else {
          // 复制其他文件
          const destPath = path.join(this.buildDir, relativePath);
          await fs.copy(filePath, destPath);
        }
        console.log(chalk.green('✅ 重新构建完成'));
      } catch (error) {
        console.error(chalk.red('❌ 重新构建失败:'), error.message);
      }
    });

    console.log(chalk.green('✅ 监听模式已启动，按 Ctrl+C 退出'));
  }
}

// 运行构建
if (require.main === module) {
  const builder = new ChromeExtensionBuilder();
  builder.build().catch(console.error);
}

module.exports = ChromeExtensionBuilder;
